import React, { useState } from 'react';
import { Row, Col, Card, Statistic, Table, DatePicker, Button } from 'antd';
import {
  DollarOutlined,
  UserOutlined,
  BarChartOutlined,
} from '@ant-design/icons';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, PieChart, Pie, Cell, LineChart, Line } from 'recharts';
import { useSelector } from 'react-redux';

const { RangePicker } = DatePicker;

const Reports = () => {
  
  const { flights } = useSelector((state) => state.flights);
  const { passengers } = useSelector((state) => state.passengers);
  const { bookings } = useSelector((state) => state.bookings);

  // 航班载客率数据
  const flightLoadRateData = flights.map(flight => ({
    name: flight.flight_number,
    loadRate: flight.total_seats > 0 ? ((flight.total_seats - flight.available_seats) / flight.total_seats * 100).toFixed(1) : 0,
    available: flight.available_seats,
    booked: flight.total_seats - flight.available_seats,
  }));

  // 收入统计数据
  const revenueData = bookings.reduce((acc, booking) => {
    const date = new Date(booking.created_at).toLocaleDateString('zh-CN');
    const existing = acc.find(item => item.date === date);
    if (existing) {
      existing.revenue += booking.total_price;
      existing.count += 1;
    } else {
      acc.push({ date, revenue: booking.total_price, count: 1 });
    }
    return acc;
  }, []).sort((a, b) => new Date(a.date) - new Date(b.date));

  // 航线收入统计
  const routeRevenueData = bookings.reduce((acc, booking) => {
    const flight = booking.flight;
    if (flight) {
      const route = `${flight.departure_city} - ${flight.arrival_city}`;
      const existing = acc.find(item => item.route === route);
      if (existing) {
        existing.revenue += booking.total_price;
        existing.count += 1;
      } else {
        acc.push({ route, revenue: booking.total_price, count: 1 });
      }
    }
    return acc;
  }, []).sort((a, b) => b.revenue - a.revenue).slice(0, 10);

  // 预订状态分布
  const bookingStatusData = [
    { name: '已确认', value: bookings.filter(b => b.status === 'confirmed').length, color: '#52c41a' },
    { name: '待确认', value: bookings.filter(b => b.status === 'pending').length, color: '#faad14' },
    { name: '已取消', value: bookings.filter(b => b.status === 'cancelled').length, color: '#ff4d4f' },
  ];



  const handleDateRangeChange = (dates) => {
    // 日期范围变化处理逻辑
    console.log('日期范围变化:', dates);
  };

  const handleExport = () => {
    // 导出报表逻辑
    console.log('导出报表...');
  };

  return (
    <div>
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1>统计报表</h1>
        <div>
          <RangePicker
            onChange={handleDateRangeChange}
            style={{ marginRight: 16 }}
          />
          <Button type="primary" onClick={handleExport}>
            导出报表
          </Button>
        </div>
      </div>

      {/* 关键指标 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总收入"
              value={bookings.reduce((sum, b) => sum + b.total_price, 0)}
              precision={2}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总预订数"
              value={bookings.length}
              prefix={<BarChartOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均客单价"
              value={bookings.length > 0 ? bookings.reduce((sum, b) => sum + b.total_price, 0) / bookings.length : 0}
              precision={2}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="乘客转化率"
              value={passengers.length > 0 ? (bookings.length / passengers.length * 100).toFixed(1) : 0}
              suffix="%"
              prefix={<UserOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="航班载客率" style={{ height: 400 }}>
            <BarChart width={500} height={300} data={flightLoadRateData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Bar dataKey="loadRate" fill="#1890ff" name="载客率(%)" />
            </BarChart>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="预订状态分布" style={{ height: 400 }}>
            <PieChart width={400} height={300}>
              <Pie
                data={bookingStatusData}
                cx={200}
                cy={150}
                labelLine={false}
                label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                outerRadius={80}
                fill="#8884d8"
                dataKey="value"
              >
                {bookingStatusData.map((entry, index) => (
                  <Cell key={`cell-${index}`} fill={entry.color} />
                ))}
              </Pie>
              <Tooltip />
            </PieChart>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="每日收入趋势" style={{ height: 400 }}>
            <LineChart width={500} height={300} data={revenueData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="date" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Line type="monotone" dataKey="revenue" stroke="#52c41a" name="收入(元)" />
            </LineChart>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="航线收入排行" style={{ height: 400 }}>
            <Table
              dataSource={routeRevenueData}
              columns={[
                { title: '航线', dataIndex: 'route', key: 'route' },
                { title: '收入', dataIndex: 'revenue', key: 'revenue', render: (text) => `¥${text}` },
                { title: '预订数', dataIndex: 'count', key: 'count' },
              ]}
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Reports;